package com.sea.app.common.kit.signature;

import com.sea.app.common.kit.Strings;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by 31417 on 2017/4/9.
 */
public enum Hmac {
    HS256("HS256","HmacSHA256", "HMAC using HS256"),
    HS384("HS384","HmacSHA384", "HMAC using SHA-384"),
    HS512("HS512","HmacSHA512", "HMAC using SHA-512");

    private final String value;
    private final String jcaName;
    private final String description;

    Hmac(String value, String jcaName, String description) {
        this.value = value;
        this.jcaName = jcaName;
        this.description = description;
    }
    public static Hmac forName(String value) {
        Hmac[] vals = values();
        int length = vals.length;

        for(int i = 0; i < length; ++i) {
            Hmac alg = vals[i];
            if(alg.value.equalsIgnoreCase(value)) {
                return alg;
            }
        }

        throw new RuntimeException(value+" :eumn not find!");
    }
    private SecretKey generalKey(String stringKey){
        byte[] encodedKey = Strings.on(stringKey).toBase64Byte();
        SecretKey key = new SecretKeySpec(encodedKey, this.jcaName);
        return key;
    }


    public byte[] compute(byte[] data,String key) {
        SecretKey secretKey = generalKey(key);
        try {
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return mac.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public String getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }
}
